package ar.com.hc.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static ar.com.hc.utils.HCResourcesUtils.getStream;

public class HCI18n {
	private static final String LANG_PROP = "LANGUAGE";

	private static final String PROP = ".properties";

	private static final String MESSAGES_FILE_PREF = "messages-";

	private Map<String, ResourceBundle> bundles;

	private String language;

	private static HCI18n INSTANCE;
	private static Logger LOGGER = LoggerFactory.getLogger(HCI18n.class);

	private HCI18n() {
		bundles = new HashMap<String, ResourceBundle>();
		setLanguage(HCConfiguration.getProperty(LANG_PROP));
	}

	public static HCI18n getInstance() {
		if (INSTANCE == null)
			INSTANCE = new HCI18n();
		return INSTANCE;
	}

	public String getMessage(String key) {
		ResourceBundle bundle = bundles.get(language);
		String message;
		try {
			message = bundle.getString(key);
		} catch (MissingResourceException e) {
			e.printStackTrace();
			message = key;
		}
		return message;

	}

	public void setLanguage(String lang) {
		try {
			loadLanguage(lang);
			this.language = lang;
		} catch (IOException e) {
			LOGGER.error("Imposible cargar el archivo de mensajes: " + lang, e);
		}

	}

	private void loadLanguage(String lang) throws IOException {

		if (!bundles.containsKey(lang))
			bundles.put(lang, new PropertyResourceBundle(
					getStream(makeFilename(lang))));

	}

	private String makeFilename(String lang) {
		return MESSAGES_FILE_PREF + lang + PROP;
	}

	public String getLanguage() {
		return language;
	}
}
